class TreeNode {
    int val;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;
    }
}

public class SortedDoublyLinkedList {
    TreeNode pre = null;
    TreeNode root = null;

    public TreeNode Convert(TreeNode pRootOfTree) {
        if(pRootOfTree == null) {
            return null;
        }

        Convert(pRootOfTree.left);

        if(root == null) {
            root = pRootOfTree;
        }
        if(pre != null) {
            pRootOfTree.left = pre;
            pre.right = pRootOfTree;
        }
        pre = pRootOfTree;

        Convert(pRootOfTree.right);

        return root;
    }

    // 用于验证结果的主方法
    public static void main(String[] args) {
        // 构建一个简单的二叉树
        TreeNode node1 = new TreeNode(1);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(3);
        node2.left = node1;
        node2.right = node3;

        SortedDoublyLinkedList solution = new SortedDoublyLinkedList();
        TreeNode head = solution.Convert(node2);

        // 遍历双向链表以验证结果
        TreeNode current = head;
        System.out.print("转换后的双向链表: ");
        while (current != null) {
            System.out.print(current.val + " ");
            current = current.right;
        }
    }
}